package com.maozzi.service.blog.domain.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maozzi.common.model.PageParam;
import com.maozzi.common.util.ParamCheckUtil;
import com.maozzi.service.blog.domain.BlogDomainService;
import com.maozzi.service.blog.repository.mapper.BlogMapper;
import com.maozzi.service.blog.repository.model.Blog;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * Blog Domain Service Impl
 *
 * @author maozi
 */
@Service
public class BlogDomainServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogDomainService {
    @Override
    public Page<Blog> page(Blog blog, PageParam pageParam) {
        ParamCheckUtil.notNull(pageParam, "分页参数错误");

        Page<Blog> page = Page.of(pageParam.getPage(), pageParam.getPageSize());
        LambdaQueryWrapper<Blog> query = Wrappers.lambdaQuery(Blog.class)
                .eq(Blog::getDeleted, false)
                .orderByDesc(Blog::getId);

        // 查询条件
        if (Objects.nonNull(blog)) {
            // 博客ID
            Long id = blog.getId();
            if (Objects.nonNull(id)) {
                query.eq(Blog::getId, id);
            }

            // 博客标题
            String title = blog.getTitle();
            if (StringUtils.hasText(title)) {
                query.likeLeft(Blog::getTitle, title);
            }

            // 博客作者
            Long userId = blog.getUserId();
            if (userId != null) {
                query.eq(Blog::getUserId, userId);
            }
        }

        return this.page(page, query);
    }

    @Override
    public void editById(Blog blog) {
        ParamCheckUtil.notNull(blog, "参数错误");
        ParamCheckUtil.notNull(blog.getId(), "id 为空");

        LambdaUpdateWrapper<Blog> query = Wrappers.lambdaUpdate(Blog.class)
                .eq(Blog::getId, blog.getId());

        this.update(blog, query);
    }

    @Override
    public void del(Long id) {
        ParamCheckUtil.notNull(id, "id 为空");

        LambdaUpdateWrapper<Blog> query = Wrappers.lambdaUpdate(Blog.class)
                .set(Blog::getDeleted, true)
                .eq(Blog::getId, id);

        this.update(query);
    }
}
